<template>
  <div class="app-container">
    <!-- 查询参数及按钮部分 -->
    <div class="filter-container">
      <el-row>
        <el-col :span="1">
          <i
            :class="[treeShow ? 'el-icon-s-fold treeI': 'el-icon-s-unfold treeI']"
            @click="toggerTree"
          />
        </el-col>
        <div class="Sign">
          <el-dialog  v-dialogDrag  
            :close-on-click-modal="false"
            :title="dialogStatus"
            :visible.sync="dialogEditFormVisible"
          >
            <el-form
              ref="dataForm"
              class="dialog-Backgroundcolor"
              :model="listQuery"
              label-position="right"
              label-width="100px"
            >
              <div class="filter-container">
                <el-row>
                  <el-form
                    label-position="right"
                    size="small"
                  >
                    <el-row>
                      <el-col :span="5">
                        <el-form-item label="变动单位：">
                          <el-select
                            v-model="listQuery.bddw"
                            class="filter-item"
                            clearable
                            placeholder="--请选择--"
                          >
                            <el-option
                              v-for="item in bddws"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>

                      <el-col :span="5">
                        <el-form-item label="工资类型：">
                          <el-select
                            v-model="listQuery.gzlx"
                            class="filter-item"
                            clearable
                            placeholder="--请选择--"
                          >
                            <el-option
                              v-for="item in gzlxs"
                              :key="item.code"
                              :label="item.name"
                              :value="item.code"
                            />
                          </el-select>
                        </el-form-item>
                      </el-col>

                    </el-row>
                    <el-button
                      type="primary"
                      style="float:right;"
                      @click="handleFilter"
                    >
                      查询
                    </el-button>
                  </el-form>
                </el-row>
              </div>
            </el-form>
          </el-dialog>
        </div>
        <div class="model">
          <el-col style="text-align: right;">
            <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
              @click="Query"
            >
              查询
            </el-button>
            <el-button
              size="small"
              class="filter-item"
              style="width:120px; margin-left: 10px;"
              type="primary"
              :loading="signLoading"
              @click="handleSign"
            >
              签报模板管理
            </el-button>

            <!-- <el-button
              size="small"
              class="filter-item"
              style="margin-left: 10px;"
              type="primary"
            >
              打印
            </el-button> -->
          </el-col>
        </div>
      </el-row>
    </div>

    <div
      ref="box"
      class="box"
    >
      <div
        class="left"
        :class="[isActive ? 'wid':'wids']"
      >
        <div
          :class="[treeShow ? 'treeShow' : 'treeNotShow']"
          :style="{'height' : treeHeight + 'px'}"
        >
          <AgencyTree
            class="agencyTree"
            @handleTreeQuery="handleTreeQuery"
          />
        </div>
      </div>
      <div
        v-show="Show"
        class="resize"
        title="收缩侧边栏"
      />
      <div
        class="mid"
        :class="[isActive ? 'mids': 'min']"
      >
        <div>
          <el-table
            ref="singalTable"
            v-loading="listLoading"
            :data="list"
            :stripe="true"
            border
            fit
            row-key="id"
            :tree-props="{children: 'children'}"
            style="width: 100%;"
            :height="tableHeight"
            :header-cell-style="{background:'#eef1f6',color:'#606266'}"
          >
            <template slot="empty">
              <tableEmpty />
            </template>
            <el-table-column
              prop="no"
              label="序号"
              align="center"
              width="80"
              fixed
            />

            <el-table-column
              label="银行名称"
              align="center"
              width="180"
              fixed
            >
              <template slot-scope="{row}">
                <span>{{ row.salaCardBank | bankFilter(that) }}</span>
              </template>
            </el-table-column>

            <el-table-column
              label="单位编码"
              align="center"
              width="120"
              fixed
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyCode }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="单位名称"
              align="center"
              width="200"
              fixed
            >
              <template slot-scope="{row}">
                <span style="float: left">{{ row.agencyName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="统发人员"
              align="center"
            >
              <el-table-column
                prop="personSum"
                label="小计"
                align="center"
              />
              <el-table-column
                prop="personEdit"
                label="在编"
                align="center"
              />
              <el-table-column
                prop="personEditLastMonth"
                label="在编比上月"
                width="100"
                align="center"
              />
              <el-table-column
                prop="personRetire"
                label="离休"
                align="center"
              />
              <el-table-column
                prop="personRetireLastMonth"
                label="离休比上月"
                width="100"
                align="center"
              />
            </el-table-column>
            <el-table-column
              label="实发工资"
              align="center"
            >

              <el-table-column
                label="小计"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.realSum ? Number(row.realSum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"):row.realSum }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="在编"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.realEdit ? Number(row.realEdit).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"):row.realEdit }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="在编比上月"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.realEditLastMonth ? Number(row.realEditLastMonth).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"):row.realEditLastMonth }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="离休"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.realRetire ? Number(row.realRetire).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"):row.realRetire }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="离休比上月"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.realRetireLastMonth ? Number(row.realRetireLastMonth).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,"):row.realRetireLastMonth }}</span>
                </template>
              </el-table-column>

            </el-table-column>

            <el-table-column
              label="应发工资"
              align="center"
            >
              <el-table-column
                label="小计"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.shouldSum ? Number(row.shouldSum).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") : row.shouldSum }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="在编"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.shouldCareer ? Number(row.shouldCareer).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") : row.shouldCareer }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="在编比上月"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.shouldCareerLastMonth ? Number(row.shouldCareerLastMonth).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") : row.shouldCareerLastMonth }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="离休"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.shouldRetire ? Number(row.shouldRetire).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") : row.shouldRetire }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="离休比上月"
                align="center"
                width="120"
              >
                <template slot-scope="{row}">
                  <span style="float: right">{{ row.shouldRetireLastMonth ? Number(row.shouldRetireLastMonth).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") : row.shouldRetireLastMonth }}</span>
                </template>
              </el-table-column>

            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
        </div>
      </div>
      <Drag ref="icon" />

    </div>

    <!-- 表格部分 -->
  </div>
</template>
<script>
import { getSalaryGrantSign } from '@/api/generateSalaryData/salaryGiveOutSign'
import { getAgencyBank } from '@/api/baseInfo'
// port { getSalaryMonthEndPage } from '@/api/financialAudit/salaryMonthEnd'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import AgencyTree from '@/components/tree/agencyTree'
import { salarySign } from '@/api/reportForm'
import Drag from '@/components/Drag'
import tableEmpty from '@/components/table/empty'
import JSZipUtils from 'jszip-utils'
// import JSZip from 'jszip'
import JSZip from 'pizzip'
import Docxtemplater from 'docxtemplater'
import { saveAs } from 'file-saver'
export default {
  name: 'SalaryGiveOutSign',
  components: { Pagination, AgencyTree, Drag, tableEmpty },
  filters: {
    bankFilter(type, that) {
      const agencyBankLists = that.agencyBankLists
      for (const item in agencyBankLists) {
        if (agencyBankLists[item].code === type) {
          return agencyBankLists[item].name
        }
      }
      return ''
    }
  },
  data() {
    return {
      treeHeight: null,
      tableHeight: null,
      dialogStatus: '',
      dialogEditFormVisible: false,
      Show: false,
      isActive: true,
      treeShow: false,
      that: this,
      list: [],
      agencyBankLists: [],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 200,
        title: undefined,
        agencyId: this.$store.getters.userInfo.agencyId,
        month: new Date(),
        bddw: '',
        gzlx: ''
      },
      bddws: [{ code: '1', name: '有变动' }, { code: '0', name: '无变动' }],
      gzlxs: [
        { code: '1', name: '事业人员' },
        { code: '0', name: '行政人员' },
        { code: '11', name: '离休人员' }
      ],
      signLoading: false,
      baseInfo: []
    }
  },
  watch: {
    list(val) {
      this.doLayout()
    }
  },
  mounted() {
    this.dragController()
    this.getTbHeight()
    this.getTeHeight()
  },
  beforeMount() {
    window.addEventListener('resize', this.getTbHeight)
    window.addEventListener('resize', this.getTeHeight)
  },
  created() {
    this.getList()
    this.initBaseInfo()
  },
  methods: {
    getTeHeight() {
      this.treeHeight = window.innerHeight - 270
    },
    doLayout() {
      this.$nextTick(() => {
        this.$refs.singalTable.doLayout()
      })
    },
    getTbHeight() {
      this.tableHeight = window.innerHeight - 220
    },
    // 拖拽
    dragController() {
      this.$refs.icon.dragControllerDiv()
    },
    // 树显隐方法
    toggerTree() {
      this.treeShow = !this.treeShow
      this.isActive = !this.isActive
      this.Show = !this.Show
    },
    // 查询
    Query() {
      this.dialogStatus = '单位上报情况查询'
      this.dialogEditFormVisible = true
    },
    getList() {
      this.listLoading = true
      getSalaryGrantSign(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total
        this.listLoading = false
      })
    },
    // 树方法
    handleTreeQuery(data) {
      this.listQuery.agencyId = data.id
      this.handleFilter()
    },
    // 更新
    handleFilter() {
      this.getList()
      this.dialogEditFormVisible = false
    },
    // 初始化基础数据
    initBaseInfo() {
      getAgencyBank().then(response => {
        this.agencyBankLists = Object.assign({}, response.data)
      })
    },
    handleSign() {
      this.signLoading = true
      salarySign().then((response) => {
        this.baseInfo = Object.assign({}, response.data)
        const _this = this
        JSZipUtils.getBinaryContent('signTemplate.docx', function(error, content) {
          // 抛出异常
          if (error) {
            _this.signLoading = false
            throw error
          }
          // 创建一个JSZip实例，内容为模板的内容
          const zip = new JSZip(content)
          // 创建并加载docxtemplater实例对象
          const doc = new Docxtemplater().loadZip(zip)
          const docInfos = []
          // 设置模板变量的值
          let agencyCount = 0
          let personSum = 0
          let workPersonSum = 0
          let retirePersonSum = 0
          let allAddPersonSum = 0
          let s1Sum = 0
          let workPlusPersonSum = 0
          let retireMinusPersonSum = 0
          let workPersonSalarySum = 0
          let retirePersonSalarySum = 0
          let allMinusS1Sum = 0
          let workMinusPersonSalarySum = 0
          let retireMinusPersonSalarySum = 0
          let salaryMonth = ''
          for (const i in _this.baseInfo) {
            const item = _this.baseInfo[i]
            // 工行
            if (item.salaCardBank === '1') {
              const ghInfos = {}
              salaryMonth = item.salaryMonth
              agencyCount += item.agencyCount
              personSum += item.personSum
              workPersonSum += item.workPersonSum
              retirePersonSum += item.retirePersonSum
              allAddPersonSum += item.allAddPersonSum
              s1Sum += item.s1Sum
              workPlusPersonSum += item.workPlusPersonSum
              retireMinusPersonSum += item.retireMinusPersonSum
              workPersonSalarySum += item.workPersonSalarySum
              retirePersonSalarySum += item.retirePersonSalarySum
              allMinusS1Sum += item.allMinusS1Sum
              workMinusPersonSalarySum += item.workMinusPersonSalarySum
              retireMinusPersonSalarySum += item.retireMinusPersonSalarySum
              ghInfos['1agencyCount'] = (item.agencyCount + '').replace('-', '')
              ghInfos['1personSum'] = (item.personSum + '').replace('-', '')
              ghInfos['1workPersonSum'] = (item.workPersonSum + '').replace('-', '')
              ghInfos['1retirePersonSum'] = (item.retirePersonSum + '').replace('-', '')
              ghInfos['1allAddPersonSum'] = (item.allAddPersonSum + '').replace('-', '')
              ghInfos['1personAllChangeFlag'] = (item.allAddPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['1workPlusPersonSum'] = (item.workPlusPersonSum + '').replace('-', '')
              ghInfos['1workAddPersonFlag'] = (item.workPlusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['1retireMinusPersonSum'] = (item.retireMinusPersonSum + '').replace('-', '')
              ghInfos['1retireAddPersonFlag'] = (item.retireMinusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['1s1Sum'] = (Number(item.s1Sum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1workPersonSalarySum'] = (Number(item.workPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1s11'] = (Number(item.s11 / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1allPlusS11'] = (Number(item.allPlusS11 / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1s11Flag'] = (item.allPlusS11 + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['1retirePersonSalarySum'] = (Number(item.retirePersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1allMinusS1Sum'] = (Number(item.allMinusS1Sum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1retireFlag'] = (item.allMinusS1Sum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['1workMinusPersonSalarySum'] = (Number(item.workMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['1retireMinusPersonSalarySum'] = (Number(item.retireMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              docInfos.push(ghInfos)
            } else if (item.salaCardBank === '2') { // 交行
              const ghInfos = {}
              agencyCount += item.agencyCount
              personSum += item.personSum
              workPersonSum += item.workPersonSum
              retirePersonSum += item.retirePersonSum
              allAddPersonSum += item.allAddPersonSum
              workPlusPersonSum += item.workPlusPersonSum
              retireMinusPersonSum += item.retireMinusPersonSum
              s1Sum += item.s1Sum
              workPersonSalarySum += item.workPersonSalarySum
              retirePersonSalarySum += item.retirePersonSalarySum
              allMinusS1Sum += item.allMinusS1Sum
              workMinusPersonSalarySum += item.workMinusPersonSalarySum
              retireMinusPersonSalarySum += item.retireMinusPersonSalarySum
              ghInfos['2agencyCount'] = (item.agencyCount + '').replace('-', '')
              ghInfos['2personSum'] = (item.personSum + '').replace('-', '')
              ghInfos['2workPersonSum'] = (item.workPersonSum + '').replace('-', '')
              ghInfos['2retirePersonSum'] = (item.retirePersonSum + '').replace('-', '')
              ghInfos['2allAddPersonSum'] = (item.allAddPersonSum + '').replace('-', '')
              ghInfos['2personAllChangeFlag'] = (item.allAddPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['2workPlusPersonSum'] = (item.workPlusPersonSum + '').replace('-', '')
              ghInfos['2workAddPersonFlag'] = (item.workPlusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['2retireMinusPersonSum'] = (item.retireMinusPersonSum + '').replace('-', '')
              ghInfos['2retireAddPersonFlag'] = (item.retireMinusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['2s1Sum'] = (Number(item.s1Sum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2workPersonSalarySum'] = (Number(item.workPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2s11'] = (Number(item.s11 / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2allPlusS11'] = (Number(item.allPlusS11 / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2s11Flag'] = (item.allPlusS11 + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['2retirePersonSalarySum'] = (Number(item.retirePersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2allMinusS1Sum'] = (Number(item.allMinusS1Sum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2retireFlag'] = (item.allMinusS1Sum + '').indexOf('-') < 0 ? '增加' : '减少'
              ghInfos['2workMinusPersonSalarySum'] = (Number(item.workMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              ghInfos['2retireMinusPersonSalarySum'] = (Number(item.retireMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
              docInfos.push(ghInfos)
            }
          }
          // 计算合计
          const ghInfos = {}
          ghInfos['agencyCount'] = (agencyCount + '').replace('-', '')
          ghInfos['personSum'] = (personSum + '').replace('-', '')
          ghInfos['workPersonSum'] = (workPersonSum + '').replace('-', '')
          ghInfos['retirePersonSum'] = (retirePersonSum + '').replace('-', '')
          ghInfos['allAddPersonSum'] = (allAddPersonSum + '').replace('-', '')
          ghInfos['personAllChangeFlag'] = (allAddPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
          ghInfos['workPlusPersonSum'] = (workPlusPersonSum + '').replace('-', '')
          ghInfos['workAddPersonFlag'] = (workPlusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
          ghInfos['retireMinusPersonSum'] = (retireMinusPersonSum + '').replace('-', '')
          ghInfos['retireAddPersonFlag'] = (retireMinusPersonSum + '').indexOf('-') < 0 ? '增加' : '减少'
          ghInfos['s1Sum'] = (Number(s1Sum / 10000).toFixed(2) + '').replace('-', '')
          ghInfos['workPersonSalarySum'] = (Number(workPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
          ghInfos['retirePersonSalarySum'] = (Number(retirePersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
          ghInfos['allMinusS1Sum'] = (Number(allMinusS1Sum / 10000).toFixed(2) + '').replace('-', '')
          ghInfos['retireFlag'] = (Number(allMinusS1Sum / 10000).toFixed(2) + '').indexOf('-') < 0 ? '增加' : '减少'
          ghInfos['workMinusPersonSalarySum'] = (Number(workMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
          ghInfos['retireMinusPersonSalarySum'] = (Number(retireMinusPersonSalarySum / 10000).toFixed(2) + '').replace('-', '')
          docInfos.push(ghInfos)
          const year = salaryMonth.split('-')[0]
          const month = salaryMonth.split('-')[1]
          const date = new Date()
          const params = { 'year': year, 'month': month, 'currentYear': date.getFullYear(),
            'currentMonth': date.getMonth() + 1, 'currentDay': date.getDate() }
          doc.setData({
            ...docInfos[0],
            ...docInfos[1],
            ...docInfos[2],
            ...params
          })
          try {
            // 用模板变量的值替换所有模板变量
            doc.render()
          } catch (error) {
            // 抛出异常
            // let e = {
            //   message: error.message,
            //   name: error.name,
            //   stack: error.stack,
            //   properties: error.properties,
            // }
            _this.$message({
              showClose: true,
              message: '生成失败！',
              type: 'success',
              duration: 4000
            })
            _this.signLoading = false
            throw error
          }

          // 生成一个代表docxtemplater对象的zip文件（不是一个真实的文件，而是在内存中的表示）
          const out = doc.getZip().generate({
            type: 'blob',
            mimeType:
              'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
          })
          // 将目标文件对象保存为目标类型的文件，并命名
          const fileName = '关于拨付' + year + '年' + month + '月份户'
          saveAs(out, fileName + '.docx')
          _this.signLoading = false
        })
      })
    }
  }
}
</script>

<style lang="scss">
@import "~@/styles/border.scss"; /*引入公共样式*/
.model .el-col-24 {
  width: 95%;
  margin-top: -4px;
}
.el-col-5 {
  width: 50%;
}
.Sign .el-dialog__body {
  padding: 10px 20px 20px 20px;
  color: #606266;
  font-size: 14px;
  word-break: break-all;
}
.Sign .el-dialog__title {
  line-height: 24px;
  font-size: 14px;
  color: #303133;
}
</style>
